using System;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Windows;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using HandyControl.Controls;
using MessageBox = HandyControl.Controls.MessageBox;
using Tryit.Views;
using SanmaoTools.Common.Untils;
using SanmaoTools.Models;
using System.Collections.Generic;
using OfficeOpenXml;
using SqlSugar.Extensions;
using System.IO;
using Microsoft.Win32;
using static Dm.util.ByteArrayQueue;
using Element = SanmaoTools.Models.Element;
using System.Windows.Documents;
using Microsoft.VisualBasic;
using Prism.Ioc;
using System.Threading;
using System.Threading.Tasks;
using System.Drawing;
using OfficeOpenXml.Style;

namespace Tryit.ViewModels
{
    public class ElementManagementViewModel : BindableBase, INavigationAware
    {
        private ObservableCollection<Element> _elements;
        public ObservableCollection<Element> Elements
        {
            get => _elements;
            set => SetProperty(ref _elements, value);
        }

        // 添加牌号列表属性
        private ObservableCollection<string> _brandList;
        public ObservableCollection<string> BrandList
        {
            get => _brandList;
            set => SetProperty(ref _brandList, value);
        }

        // 添加选中的牌号属性
        private string _selectedBrand;
        public string SelectedBrand
        {
            get => _selectedBrand;
            set
            {
                if (SetProperty(ref _selectedBrand, value))
                {
                    FilterElementsByBrand();
                }
            }
        }

        // 添加日期范围属性
        private DateTime? _startDate;
        public DateTime? StartDate
        {
            get => _startDate;
            set
            {
                if (SetProperty(ref _startDate, value))
                {
                    FilterElementsByDate();
                }
            }
        }

        private DateTime? _endDate;
        public DateTime? EndDate
        {
            get => _endDate;
            set
            {
                if (SetProperty(ref _endDate, value))
                {
                    FilterElementsByDate();
                }
            }
        }

        // 添加显示类型枚举
        public enum DisplayType
        {
            Composition,    // 成分信息
            Physical       // 物理性能
        }

        // 添加当前显示类型属性
        private DisplayType _currentDisplayType = DisplayType.Composition;
        public DisplayType CurrentDisplayType
        {
            get => _currentDisplayType;
            set
            {
                if (SetProperty(ref _currentDisplayType, value))
                {
                    UpdateDisplayType();
                }
            }
        }

        // 添加显示类型更新方法
        private void UpdateDisplayType()
        {
            // 触发属性变更通知，用于更新UI
            RaisePropertyChanged(nameof(IsCompositionVisible));
            RaisePropertyChanged(nameof(IsPhysicalVisible));
            RaisePropertyChanged(nameof(IsDateFilterVisible));
            RaisePropertyChanged(nameof(IsBrandSearchVisible));

            // 根据当前显示类型更新分页信息
            if (CurrentDisplayType == DisplayType.Composition)
            {
                UpdatePagedElements();
            }
            else
            {
                UpdatePagedPhysicalProperties();
            }
        }

        // 添加可见性属性
        public bool IsCompositionVisible => CurrentDisplayType == DisplayType.Composition;
        public bool IsPhysicalVisible => CurrentDisplayType == DisplayType.Physical;
        public bool IsDateFilterVisible => CurrentDisplayType == DisplayType.Composition;
        public bool IsBrandSearchVisible => CurrentDisplayType == DisplayType.Physical;

        private ObservableCollection<Element> _currentPageElements;
        public ObservableCollection<Element> CurrentPageElements
        {
            get => _currentPageElements;
            set => SetProperty(ref _currentPageElements, value);
        }
        public List<Element> ElementList { get; set; }
        private Element _selectedElement;
        public Element SelectedElement
        {
            get => _selectedElement;
            set => SetProperty(ref _selectedElement, value);
        }

        // 分页相关属性
        private int _currentPage = 1;
        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        private int _pageSize = 10;
        public int PageSize
        {
            get => _pageSize;
            set
            {
                if (SetProperty(ref _pageSize, value))
                {
                    CurrentPage = 1;
                    UpdatePagedElements();
                }
            }
        }

        private int _totalPages;
        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }

        private int _totalItems;
        public int TotalItems
        {
            get => _totalItems;
            set => SetProperty(ref _totalItems, value);
        }
        private string _pageInfo;
        public string PageInfo
        {
            get => $"第 {CurrentPage} 页，共 {TotalPages} 页，共 {TotalItems} 条记录";
            set => SetProperty(ref _pageInfo, value);
        }

        public List<int> PageSizes { get; } = new List<int> { 10, 20, 50, 100 };

        // 分页命令
        public DelegateCommand FirstPageCommand { get; }
        public DelegateCommand PreviousPageCommand { get; }
        public DelegateCommand NextPageCommand { get; }
        public DelegateCommand LastPageCommand { get; }
        public DelegateCommand GoToPageCommand { get; }

        // 原有的命令
        public DelegateCommand EditCommand { get; }
        public DelegateCommand DeleteCommand { get; }
        public DelegateCommand RefreshCommand { get; }
        public DelegateCommand AddBatchCommand { get; }
        public DelegateCommand ArchiveCommand { get; }
        public DelegateCommand ManagePersonCommand { get; }

        // 添加物理性能相关的命令
        public DelegateCommand PhysicalEditCommand { get; }
        public DelegateCommand PhysicalDeleteCommand { get; }
        public DelegateCommand PhysicalRefreshCommand { get; }
        public DelegateCommand PhysicalAddBatchCommand { get; }
        public DelegateCommand PhysicalExportCommand { get; }

        private int _pageInput;
        public int PageInput
        {
            get => _pageInput;
            set => SetProperty(ref _pageInput, value);
        }

        public SqlSugarHelper SqlSugarHelper { get; set; }

        // 添加清除日期筛选的方法
        public DelegateCommand ClearDateFilterCommand { get; }

        private string _searchText;
        public string SearchText
        {
            get => _searchText;
            set
            {
                if (SetProperty(ref _searchText, value))
                {
                    if (CurrentDisplayType == DisplayType.Physical)
                    {
                        FilterElementsByBrandSearch();
                    }
                }
            }
        }

        // 添加搜索命令
        public DelegateCommand SearchCommand { get; }

        private ObservableCollection<PhysicalProperties> _physicalProperties;
        public ObservableCollection<PhysicalProperties> PhysicalProperties
        {
            get => _physicalProperties;
            set => SetProperty(ref _physicalProperties, value);
        }

        private PhysicalProperties _selectedPhysicalProperty;
        public PhysicalProperties SelectedPhysicalProperty
        {
            get => _selectedPhysicalProperty;
            set => SetProperty(ref _selectedPhysicalProperty, value);
        }

        private ObservableCollection<PhysicalProperties> _selectedPhysicalProperties;
        public ObservableCollection<PhysicalProperties> SelectedPhysicalProperties
        {
            get => _selectedPhysicalProperties;
            set => SetProperty(ref _selectedPhysicalProperties, value);
        }

        private ObservableCollection<Element> _selectedElements;
        public ObservableCollection<Element> SelectedElements
        {
            get => _selectedElements;
            set => SetProperty(ref _selectedElements, value);
        }

        private string _physicalSearchText;
        public string PhysicalSearchText
        {
            get => _physicalSearchText;
            set
            {
                if (SetProperty(ref _physicalSearchText, value))
                {
                    FilterPhysicalPropertiesByBrand();
                }
            }
        }

        // 添加物理性能搜索命令
        public DelegateCommand PhysicalSearchCommand { get; }

        // 添加导出命令
        public DelegateCommand ExportCommand { get; }

        public DelegateCommand ShowBrandCountCommand { get; }

        public ElementManagementViewModel()
        {
            SqlSugarHelper = new SqlSugarHelper();
            Elements = new ObservableCollection<Element>();
            PhysicalProperties = new ObservableCollection<PhysicalProperties>();
            SelectedPhysicalProperties = new ObservableCollection<PhysicalProperties>();
            SelectedElements = new ObservableCollection<Element>();
            CurrentPageElements = new ObservableCollection<Element>();
            BrandList = new ObservableCollection<string>();
            PageInfo = $"第 {CurrentPage} 页，共 {TotalPages} 页，共 {TotalItems} 条记录";

            // 初始化搜索命令
            SearchCommand = new DelegateCommand(() =>
            {
                FilterElementsByBrandSearch();
            });

            // 初始化物理性能搜索命令
            PhysicalSearchCommand = new DelegateCommand(() =>
            {
                FilterPhysicalPropertiesByBrand();
            });

            // 初始化清除日期筛选命令
            ClearDateFilterCommand = new DelegateCommand(() =>
            {
                StartDate = null;
                EndDate = null;
            });

            // 初始化分页命令
            FirstPageCommand = new DelegateCommand(ExecuteFirstPage);
            PreviousPageCommand = new DelegateCommand(ExecutePreviousPage, CanExecutePreviousPage)
                .ObservesProperty(() => CurrentPage);
            NextPageCommand = new DelegateCommand(ExecuteNextPage, CanExecuteNextPage)
                .ObservesProperty(() => CurrentPage)
                .ObservesProperty(() => TotalPages);
            LastPageCommand = new DelegateCommand(ExecuteLastPage);
            GoToPageCommand = new DelegateCommand(ExecuteGoToPage, CanExecuteGoToPage)
                .ObservesProperty(() => PageInput)
                .ObservesProperty(() => TotalPages);

            // 初始化原有命令
            AddBatchCommand = new DelegateCommand(ExecuteAddBatch);
            EditCommand = new DelegateCommand(() => ExecuteAddOrEdit(SelectedElement))
                .ObservesProperty(() => SelectedElement);
            DeleteCommand = new DelegateCommand(ExecuteDelete, CanExecuteEditDelete)
                .ObservesProperty(() => SelectedElement)
                .ObservesProperty(() => SelectedElements);
            RefreshCommand = new DelegateCommand(ExecuteRefresh);
            ArchiveCommand = new DelegateCommand(ExecuteArchive);
            ManagePersonCommand = new DelegateCommand(ExecuteManagePerson);

            // 初始化物理性能相关命令
            PhysicalEditCommand = new DelegateCommand(() => ExecutePhysicalAddOrEdit(SelectedPhysicalProperty))
                .ObservesProperty(() => SelectedPhysicalProperty);
            PhysicalDeleteCommand = new DelegateCommand(ExecutePhysicalDelete, CanExecutePhysicalEditDelete)
                .ObservesProperty(() => SelectedPhysicalProperty)
                .ObservesProperty(() => SelectedPhysicalProperties);
            PhysicalRefreshCommand = new DelegateCommand(ExecutePhysicalRefresh);
            PhysicalExportCommand = new DelegateCommand(ExecutePhysicalExport);

            // 初始化导出命令
            ExportCommand = new DelegateCommand(ExecuteExport);

            ShowBrandCountCommand = new DelegateCommand(ShowBrandCount);

            LoadElements();
            LoadPhysicalProperties();
        }

        private void ShowBrandCount()
        {
            // 按当前日期范围筛选
            var filtered = Elements.ToList();
            if (StartDate.HasValue)
            {
                filtered = filtered.Where(e => e.Date >= StartDate.Value).ToList();
            }
            if (EndDate.HasValue)
            {
                filtered = filtered.Where(e => e.Date <= EndDate.Value.AddDays(1).AddSeconds(-1)).ToList();
            }
            // 统计牌号及数量
            var brandGroups = filtered
                .Where(e => !string.IsNullOrWhiteSpace(e.Brand))
                .GroupBy(e => e.Brand)
                .Select(g => new { Brand = g.Key, Count = g.Count() })
                .OrderByDescending(g => g.Count)
                .ToList();
            if (brandGroups.Count == 0)
            {
                MessageBox.Show("所选范围内没有数据", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            // 生成统计文本
            var text = string.Join("\n", brandGroups.Select(g => $"{g.Brand}, 数量: {g.Count}包"));
            text = $"该日期范围共生产{brandGroups.Count}炉：\n" + text;
            // 复制到剪切板
            System.Windows.Clipboard.SetText(text);
            MessageBox.Show(text + "\n\n已复制到剪切板", "牌号统计", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void ExecuteAddBatch()
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Excel文件|*.xlsx",
                Title = "选择Excel文件",
                ValidateNames = true,
                CheckFileExists = true,
                Multiselect = true
            };
            if (openFileDialog.ShowDialog() == true)
            {
                ElementList = new List<Element>();
                var failedFiles = new List<string>();
                var successCount = 0;

                foreach (var item in openFileDialog.FileNames)
                {
                    try
                {
                    var temp = ProcessExcelFileBatch(item);
                    ElementList.Add(temp);
                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        failedFiles.Add($"{Path.GetFileName(item)}: {ex.Message}");
                        continue;
                    }
                }

                if (ElementList.Any())
                {
                try
                {
                using (var db = SqlSugarHelper.GetInstance())
                {
                        // 检查每个元素的牌号和中转包次号组合是否已存在
                        var duplicateElements = new List<Element>();
                        foreach (var element in ElementList)
                        {
                            var existingElement = db.Queryable<Element>()
                                .Where(it => it.Brand == element.Brand && it.Transfernumber == element.Transfernumber)
                                .First();
                            
                            if (existingElement != null)
                            {
                                duplicateElements.Add(element);
                            }
                        }

                        if (duplicateElements.Any())
                        {
                            var duplicateInfo = string.Join("\n", duplicateElements.Select(e => 
                                $"牌号: {e.Brand}, 中转包次号: {e.Transfernumber}"));
                            MessageBox.Show($"以下数据已存在，请检查：\n{duplicateInfo}", 
                                "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        // 如果没有重复数据，执行插入操作
                    db.Insertable(ElementList).ExecuteCommand();
                        
                        // 更新牌号列表
                        var re = db.Queryable<BrandAndStoveNumber>().Select(it => it.Name).ToList();
                        var Brandlist = ElementList.Select(it => it.Brand).Distinct().ToList();
                        List<BrandAndStoveNumber> listadd = new List<BrandAndStoveNumber>();
                        foreach (var item in Brandlist)
                        {
                            if (re.Count > 0)
                            {
                                if (!re.Contains(item)) listadd.Add(new BrandAndStoveNumber() { Name = item, CreateTime = DateTime.Now, UpdateTime = DateTime.Now });
                            }
                            else
                            {
                                listadd.Add(new BrandAndStoveNumber() { Name = item, CreateTime = DateTime.Now, UpdateTime = DateTime.Now });
                            }
                        }
                            if (listadd.Any())
                            {
                        db.Insertable(listadd).ExecuteCommand();
                            }
                        
                    LoadElements();  // 重新加载数据
                    UpdatePagedElements();  // 更新分页信息

                            // 显示处理结果
                            var message = $"成功处理 {successCount} 个文件";
                            if (failedFiles.Any())
                            {
                                message += $"\n\n处理失败的文件：\n{string.Join("\n", failedFiles)}";
                            }
                            MessageBox.Show(message, "处理结果", MessageBoxButton.OK, 
                                failedFiles.Any() ? MessageBoxImage.Warning : MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                        MessageBox.Show($"保存数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else if (failedFiles.Any())
                {
                    MessageBox.Show($"所有文件处理失败：\n{string.Join("\n", failedFiles)}", 
                        "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        public void UpdatePagedElements()
        {
            if (Elements == null || !Elements.Any())
            {
                CurrentPageElements.Clear();
                TotalItems = 0;
                TotalPages = 0;
                CurrentPage = 1;
                RaisePropertyChanged(nameof(PageInfo));
                return;
            }

            TotalItems = Elements.Count;
            TotalPages = (int)Math.Ceiling((double)TotalItems / PageSize);

            // 确保当前页在有效范围内
            if (CurrentPage > TotalPages)
            {
                CurrentPage = TotalPages;
            }
            else if (CurrentPage < 1)
            {
                CurrentPage = 1;
            }

            var startIndex = (CurrentPage - 1) * PageSize;
            var count = Math.Min(PageSize, TotalItems - startIndex);

            CurrentPageElements.Clear();
            foreach (var element in Elements.Skip(startIndex).Take(count))
            {
                CurrentPageElements.Add(element);
            }

            // 显式通知 PageInfo 属性变更
            RaisePropertyChanged(nameof(PageInfo));
        }

        private void ExecuteFirstPage()
        {
            CurrentPage = 1;
            if (CurrentDisplayType == DisplayType.Composition)
            {
            UpdatePagedElements();
            }
            else
            {
                UpdatePagedPhysicalProperties();
            }
        }

        private void ExecutePreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                if (CurrentDisplayType == DisplayType.Composition)
                {
                UpdatePagedElements();
                }
                else
                {
                    UpdatePagedPhysicalProperties();
                }
            }
        }

        private bool CanExecutePreviousPage()
        {
            return CurrentPage > 1;
        }

        private void ExecuteNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                if (CurrentDisplayType == DisplayType.Composition)
                {
                UpdatePagedElements();
                }
                else
                {
                    UpdatePagedPhysicalProperties();
                }
            }
        }

        private bool CanExecuteNextPage()
        {
            return CurrentPage < TotalPages;
        }

        private void ExecuteLastPage()
        {
            CurrentPage = TotalPages;
            if (CurrentDisplayType == DisplayType.Composition)
            {
            UpdatePagedElements();
            }
            else
            {
                UpdatePagedPhysicalProperties();
            }
        }

        private bool CanExecuteGoToPage()
        {
            return PageInput > 0 && PageInput <= TotalPages;
        }

        private void ExecuteGoToPage()
        {
            if (PageInput > 0 && PageInput <= TotalPages)
            {
                CurrentPage = PageInput;
                if (CurrentDisplayType == DisplayType.Composition)
                {
                UpdatePagedElements();
                }
                else
                {
                    UpdatePagedPhysicalProperties();
                }
            }
        }

        public void LoadElements()
        {
            try
            {
                using (var db = new SqlSugarHelper().GetInstance())
                {
                    var query = db.Queryable<Element>()
                        .Select(it => new Element
                        {
                            Id = it.Id,
                            Date = it.Date,
                            Brand = it.Brand,
                            Transfernumber = it.Transfernumber,
                            Al = it.Al,
                            Si = it.Si,
                            Fe = it.Fe,
                            Cu = it.Cu,
                            Mn = it.Mn,
                            Mg = it.Mg,
                            Cr = it.Cr,
                            Ni = it.Ni,
                            Zn = it.Zn,
                            Ti = it.Ti,
                            Be = it.Be,
                            Ca = it.Ca,
                            Co = it.Co,
                            Ga = it.Ga,
                            Na = it.Na,
                            P = it.P,
                            Pb = it.Pb,
                            Sb = it.Sb,
                            Sn = it.Sn,
                            Sr = it.Sr,
                            V = it.V,
                            Zr = it.Zr,
                            IsArchived = it.IsArchived,
                            ArchiveTime = it.ArchiveTime,
                            ArchiveBatchNumber = it.ArchiveBatchNumber,
                            CreateTime = it.CreateTime,
                            UpdateTime = it.UpdateTime
                        });

                    // 应用搜索条件
                    if (!string.IsNullOrEmpty(SearchText))
                    {
                        query = query.Where(it => it.Brand.Contains(SearchText) || 
                                                it.Transfernumber.Contains(SearchText));
                    }

                    var elements = query.OrderByDescending(it => it.Id).ToList();
                    Elements.Clear();
                    foreach (var element in elements)
                    {
                        Elements.Add(element);
                    }
                    UpdatePagedElements();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public Element ProcessExcelFileBatch(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException("找不到指定的文件。", filePath);
                }

                // 设置超时时间
                using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
                {
                    try
                    {
                using (var package = new ExcelPackage(new FileInfo(filePath)))
                {
                    var workbook = package.Workbook;
                    if (workbook.Worksheets.Count == 0)
                    {
                        throw new Exception("Excel文件中没有工作表。");
                    }

                    var worksheet = workbook.Worksheets[0];
                    if (worksheet.Dimension == null)
                    {
                        throw new Exception("工作表是空的。");
                    }

                    var endRow = worksheet.Dimension.End.Row;
                    var endColumn = worksheet.Dimension.End.Column;

                    if (endRow < 2)
                    {
                        throw new Exception("Excel文件中数据行数不足。");
                    }

                    // 创建数据表来存储Excel数据
                    var dataTable = new System.Data.DataTable();
                    dataTable.TableName = Path.GetFileNameWithoutExtension(filePath);

                    // 添加列
                    for (int col = 1; col <= endColumn; col++)
                    {
                        var columnName = worksheet.Cells[1, col].Text.ToString();
                        if (string.IsNullOrEmpty(columnName))
                        {
                            columnName = $"Column {col}";
                        }
                        if (col == 1) columnName = "日期";
                        // 检查列名是否已存在
                        if (dataTable.Columns.Contains(columnName))
                        {
                            columnName = $"{columnName}_{col}";
                        }

                        dataTable.Columns.Add(columnName);
                    }

                    // 添加数据行
                    for (int row = 2; row <= endRow; row++)
                    {
                                cts.Token.ThrowIfCancellationRequested();
                        var dataRow = dataTable.NewRow();
                        for (int col = 1; col <= endColumn; col++)
                        {
                                    dataRow[col - 1] = worksheet.Cells[row, col].Text.ToString();
                        }
                        dataTable.Rows.Add(dataRow);
                    }

                    Element element = new Element();
                            try
                            {
                                // 验证日期格式
                                if (!DateTime.TryParse(dataTable.Rows[1]["日期"].ToString(), out DateTime date))
                                {
                                    throw new FormatException("日期格式不正确");
                                }
                                element.Date = date;

                                // 验证牌号和中转包次号格式
                    string[] sp = dataTable.Rows[1]["??"].ToString().Split('-');
                                if (sp.Length < 4)
                                {
                                    throw new FormatException("牌号格式不正确");
                                }
                    element.Brand = sp[0] + "-" + sp[1] + "-" + sp[2];
                    element.Transfernumber = sp[3];

                                // 验证数值格式
                                string[] numericColumns = { "Result", "Result_5", "Result_6", "Result_7", "Result_8", "Result_9", 
                                    "Result_10", "Result_11", "Result_12", "Result_13", "Result_14", "Result_15", "Result_16", 
                                    "Result_17", "Result_18", "Result_19", "Result_20", "Result_21", "Result_22", "Result_23", 
                                    "Result_24", "Result_25" };

                                foreach (var col in numericColumns)
                                {
                                    if (dataTable.Columns.Contains(col))
                                    {
                                        string value = dataTable.Rows[1][col].ToString();
                                        if (!string.IsNullOrEmpty(value))
                                        {
                                            if (!double.TryParse(value.Replace("%", ""), out _))
                                            {
                                                throw new FormatException($"列 {col} 的数值格式不正确");
                                            }
                                        }
                                    }
                                }

                                // 设置元素属性
                    element.Al = dataTable.Rows[1]["Result"].ToString();
                    element.Si = dataTable.Rows[1]["Result_5"].ToString();
                    element.Fe = dataTable.Rows[1]["Result_6"].ToString();
                    element.Cu = dataTable.Rows[1]["Result_7"].ToString();
                    element.Mn = dataTable.Rows[1]["Result_8"].ToString();
                    element.Mg = dataTable.Rows[1]["Result_9"].ToString();
                    element.Cr = dataTable.Rows[1]["Result_10"].ToString();
                    element.Ni = dataTable.Rows[1]["Result_11"].ToString();
                    element.Zn = dataTable.Rows[1]["Result_12"].ToString();
                    element.Ti = dataTable.Rows[1]["Result_13"].ToString();
                    element.Be = dataTable.Rows[1]["Result_14"].ToString();
                    element.Ca = dataTable.Rows[1]["Result_15"].ToString();
                    element.Co = dataTable.Rows[1]["Result_16"].ToString();
                    element.Ga = dataTable.Rows[1]["Result_17"].ToString();
                    element.Na = dataTable.Rows[1]["Result_18"].ToString();
                    element.P = dataTable.Rows[1]["Result_19"].ToString();
                    element.Pb = dataTable.Rows[1]["Result_20"].ToString();
                    element.Sb = dataTable.Rows[1]["Result_21"].ToString();
                    element.Sn = dataTable.Rows[1]["Result_22"].ToString();
                    element.Sr = dataTable.Rows[1]["Result_23"].ToString();
                    element.V = dataTable.Rows[1]["Result_24"].ToString();
                    element.Zr = dataTable.Rows[1]["Result_25"].ToString();
                    element.CreateTime = DateTime.Now;
                    element.UpdateTime = DateTime.Now;

                    return element;
                            }
                            catch (FormatException ex)
                            {
                                throw new FormatException($"Excel文件格式错误: {ex.Message}");
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        throw new TimeoutException("处理Excel文件超时");
                }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"处理Excel文件失败: {ex.Message}");
            }
        }
        private void ExecuteAddOrEdit(Element selectedElement)
        {
            var element = selectedElement == null
                ? new Element { CreateTime = DateTime.Now, UpdateTime = DateTime.Now }
                : new Element
                {
                    Id = selectedElement.Id,
                    Date = selectedElement.Date,
                    Brand = selectedElement.Brand,
                    Transfernumber = selectedElement.Transfernumber,
                    Al = selectedElement.Al,
                    Si = selectedElement.Si,
                    Fe = selectedElement.Fe,
                    Cu = selectedElement.Cu,
                    Mg = selectedElement.Mg,
                    Sb = selectedElement.Sb,
                    Mn = selectedElement.Mn,
                    Cr = selectedElement.Cr,
                    Ni = selectedElement.Ni,
                    Zn = selectedElement.Zn,
                    Ti = selectedElement.Ti,
                    Be = selectedElement.Be,
                    Ca = selectedElement.Ca,
                    Co = selectedElement.Co,
                    Ga = selectedElement.Ga,
                    Na = selectedElement.Na,
                    P = selectedElement.P,
                    Pb = selectedElement.Pb,
                    Sn = selectedElement.Sn,
                    Sr = selectedElement.Sr,
                    V = selectedElement.V,
                    Zr = selectedElement.Zr,
                    CreateTime = selectedElement.CreateTime,
                UpdateTime = DateTime.Now
            };

            var dialog = new ElementEditDialog(element);
            if (dialog.ShowDialog() == true)
            {
                try
                {
                    using (var db = SqlSugarHelper.GetInstance())
                    {
                        if (selectedElement == null)
                        {
                            // 检查牌号和中转包次号组合是否已存在
                            var existingElement = db.Queryable<Element>()
                                .Where(it => it.Brand == element.Brand && it.Transfernumber == element.Transfernumber)
                                .First();
                            
                            if (existingElement != null)
                            {
                                MessageBox.Show($"牌号 {element.Brand} 与中转包次号 {element.Transfernumber} 的组合已存在，请检查输入", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            // 添加操作
                            int re = db.Queryable<BrandAndStoveNumber>().Where(it => it.Name == element.Brand).Count();
                            if (re == 0)
                            {
                                // 添加操作
                                BrandAndStoveNumber brandAndStoveNumber = new BrandAndStoveNumber();
                                brandAndStoveNumber.Name = element.Brand;
                                brandAndStoveNumber.CreateTime = DateTime.Now;
                                brandAndStoveNumber.UpdateTime = DateTime.Now;
                                int res = db.Insertable(brandAndStoveNumber).ExecuteCommand();
                            }
                        db.Insertable(element).ExecuteCommand();
                        Elements.Add(element);
                            MessageBox.Show("添加成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            // 编辑操作时，检查新牌号和中转包次号组合是否与其他记录重复
                            var existingElement = db.Queryable<Element>()
                                .Where(it => it.Brand == element.Brand && 
                                           it.Transfernumber == element.Transfernumber && 
                                           it.Id != element.Id)
                                .First();
                            
                            if (existingElement != null)
                            {
                                MessageBox.Show($"牌号 {element.Brand} 与中转包次号 {element.Transfernumber} 的组合已存在，请检查输入", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            // 编辑操作
                            db.Updateable(element).ExecuteCommand();
                            var index = Elements.IndexOf(SelectedElement);
                            Elements[index] = element;
                            SelectedElement = element;
                            MessageBox.Show("修改成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        UpdatePagedElements();
                        ExecuteRefresh();
                    }
                }
                catch (Exception ex)
                {
                    if (selectedElement == null) 
                    MessageBox.Show($"添加失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    else 
                        MessageBox.Show($"修改失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private bool CanExecuteEditDelete()
        {
            return SelectedElement != null || (SelectedElements != null && SelectedElements.Any());
        }

        private void ExecuteDelete()
        {
            if (SelectedElement == null && (SelectedElements == null || !SelectedElements.Any())) return;

            var message = SelectedElements != null && SelectedElements.Any()
                ? $"确定要删除选中的 {SelectedElements.Count} 条成分信息数据吗？"
                : "确定要删除选中的成分信息数据吗？";

            if (MessageBox.Show(message, "确认", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                try
                {
                    using (var db = SqlSugarHelper.GetInstance())
                    {
                        if (SelectedElements != null && SelectedElements.Any())
                        {
                            // 批量删除
                            var ids = SelectedElements.Select(e => e.Id).ToList();
                            db.Deleteable<Element>().Where(it => ids.Contains(it.Id)).ExecuteCommand();
                            
                            // 从集合中移除已删除的项
                            foreach (var element in SelectedElements.ToList())
                            {
                                Elements.Remove(element);
                            }
                            SelectedElements.Clear();
                        }
                        else if (SelectedElement != null)
                        {
                            // 单个删除
                            db.Deleteable<Element>().Where(it => it.Id == SelectedElement.Id).ExecuteCommand();
                            Elements.Remove(SelectedElement);
                        }

                        UpdatePagedElements();
                        ExecuteRefresh();
                        MessageBox.Show("删除成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void ExecuteRefresh()
        {
            LoadElements();
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            LoadElements();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }

        // 添加按牌号筛选的方法
        private void FilterElementsByBrand()
        {
            try
            {
                using (var db = SqlSugarHelper.GetInstance())
                {
                    var query = db.Queryable<Element>();

                    if (!string.IsNullOrEmpty(SelectedBrand) && SelectedBrand != "全部")
                    {
                        query = query.Where(it => it.Brand == SelectedBrand);
                    }

                    var elements = query.OrderByDescending(it => it.Id).ToList();
                    Elements.Clear();
                    foreach (var element in elements)
                    {
                        Elements.Add(element);
                    }
                    UpdatePagedElements();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"筛选数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 添加按日期范围筛选的方法
        private void FilterElementsByDate()
        {
            try
            {
                using (var db = SqlSugarHelper.GetInstance())
                {
                    var query = db.Queryable<Element>();

                    if (StartDate.HasValue)
                    {
                        query = query.Where(it => it.Date >= StartDate.Value);
                    }

                    if (EndDate.HasValue)
                    {
                        query = query.Where(it => it.Date <= EndDate.Value.AddDays(1).AddSeconds(-1)); // 包含结束日期
                    }

                    var elements = query.OrderByDescending(it => it.Id).ToList();
                    Elements.Clear();
                    foreach (var element in elements)
                    {
                        Elements.Add(element);
                    }
                    UpdatePagedElements();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"日期筛选失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecutePhysicalAddOrEdit(PhysicalProperties selectedProperty)
        {
            var property = selectedProperty == null
                ? new PhysicalProperties { CreateTime = DateTime.Now, UpdateTime = DateTime.Now }
                : new PhysicalProperties
                {
                    Id = selectedProperty.Id,
                    Date = selectedProperty.Date,
                    Brand = selectedProperty.Brand,
                    TensileStrength = selectedProperty.TensileStrength,
                    YieldStrength = selectedProperty.YieldStrength,
                    Elongation = selectedProperty.Elongation,
                    Hardness = selectedProperty.Hardness,
                    CreateTime = selectedProperty.CreateTime,
                UpdateTime = DateTime.Now
            };

            var dialog = new PhysicalPropertiesEditDialog(property);
            if (dialog.ShowDialog() == true)
            {
                try
                {
                    using (var db = SqlSugarHelper.GetInstance())
                    {
                        if (selectedProperty == null)
                        {
                            // 检查牌号是否已存在
                            var existingProperty = db.Queryable<PhysicalProperties>()
                                .Where(it => it.Brand == property.Brand)
                                .First();
                            
                            if (existingProperty != null)
                            {
                                MessageBox.Show($"牌号 {property.Brand} 已存在，请使用其他牌号", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            // 添加操作
                            property.CreateTime = DateTime.Now;
                            property.UpdateTime = DateTime.Now;
                            db.Insertable(property).ExecuteCommand();
                            PhysicalProperties.Add(property);
                            MessageBox.Show("添加成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            // 编辑操作时，检查新牌号是否与其他记录重复
                            var existingProperty = db.Queryable<PhysicalProperties>()
                                .Where(it => it.Brand == property.Brand && it.Id != property.Id)
                                .First();
                            
                            if (existingProperty != null)
                            {
                                MessageBox.Show($"牌号 {property.Brand} 已存在，请使用其他牌号", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            // 编辑操作
                            db.Updateable(property).ExecuteCommand();
                            var index = PhysicalProperties.IndexOf(SelectedPhysicalProperty);
                            PhysicalProperties[index] = property;
                            SelectedPhysicalProperty = property;
                        MessageBox.Show("修改成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        ExecutePhysicalRefresh();
                    }
                }
                catch (Exception ex)
                {
                    if (selectedProperty == null)
                        MessageBox.Show($"添加失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    MessageBox.Show($"修改失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private bool CanExecutePhysicalEditDelete()
        {
            return SelectedPhysicalProperty != null || (SelectedPhysicalProperties != null && SelectedPhysicalProperties.Any());
        }

        private void ExecutePhysicalDelete()
        {
            if (SelectedPhysicalProperty == null && (SelectedPhysicalProperties == null || !SelectedPhysicalProperties.Any())) return;

            var message = SelectedPhysicalProperties != null && SelectedPhysicalProperties.Any()
                ? $"确定要删除选中的 {SelectedPhysicalProperties.Count} 条物理性能数据吗？"
                : "确定要删除选中的物理性能数据吗？";

            if (MessageBox.Show(message, "确认", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                try
                {
                    using (var db = SqlSugarHelper.GetInstance())
                    {
                        if (SelectedPhysicalProperties != null && SelectedPhysicalProperties.Any())
                        {
                            // 批量删除
                            var ids = SelectedPhysicalProperties.Select(p => p.Id).ToList();
                            db.Deleteable<PhysicalProperties>().Where(it => ids.Contains(it.Id)).ExecuteCommand();
                            
                            // 从集合中移除已删除的项
                            foreach (var property in SelectedPhysicalProperties.ToList())
                            {
                                PhysicalProperties.Remove(property);
                            }
                            SelectedPhysicalProperties.Clear();
                        }
                        else if (SelectedPhysicalProperty != null)
                        {
                            // 单个删除
                            db.Deleteable<PhysicalProperties>().Where(it => it.Id == SelectedPhysicalProperty.Id).ExecuteCommand();
                            PhysicalProperties.Remove(SelectedPhysicalProperty);
                        }

                        ExecutePhysicalRefresh();
                        MessageBox.Show("删除成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void ExecutePhysicalRefresh()
        {
            LoadPhysicalProperties();
        }

        private void LoadPhysicalProperties()
        {
            try
            {
                using (var db = SqlSugarHelper.GetInstance())
                {
                    var properties = db.Queryable<PhysicalProperties>()
                        .OrderByDescending(it => it.Id)
                        .ToList();
                    PhysicalProperties.Clear();
                    foreach (var property in properties)
                    {
                        PhysicalProperties.Add(property);
                    }
                    UpdatePagedPhysicalProperties();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载物理性能数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void FilterElementsByBrandSearch()
        {
            try
            {
                using (var db = SqlSugarHelper.GetInstance())
                {
                    var query = db.Queryable<Element>()
                        .MergeTable()
                        .LeftJoin<Archive>((e, a) => e.ArchiveId == a.Id)
                        .Select((e, a) => new Element
                        {
                            Id = e.Id,
                            Date = e.Date,
                            Brand = e.Brand,
                            Transfernumber = e.Transfernumber,
                            Al = e.Al,
                            Si = e.Si,
                            Fe = e.Fe,
                            Cu = e.Cu,
                            Mn = e.Mn,
                            Mg = e.Mg,
                            Cr = e.Cr,
                            Ni = e.Ni,
                            Zn = e.Zn,
                            Ti = e.Ti,
                            Be = e.Be,
                            Ca = e.Ca,
                            Co = e.Co,
                            Ga = e.Ga,
                            Na = e.Na,
                            P = e.P,
                            Pb = e.Pb,
                            Sb = e.Sb,
                            Sn = e.Sn,
                            Sr = e.Sr,
                            V = e.V,
                            Zr = e.Zr,
                            IsArchived = e.IsArchived,
                            ArchiveId = e.ArchiveId,
                            ArchiveTime = e.ArchiveTime,
                            ArchiveBatchNumber = e.ArchiveBatchNumber,
                            CreateTime = e.CreateTime,
                            UpdateTime = e.UpdateTime
                        });

                    // 处理下拉框选择
                    if (!string.IsNullOrEmpty(SelectedBrand) && SelectedBrand != "全部")
                    {
                        query = query.Where(e => e.Brand == SelectedBrand);
                    }

                    // 处理搜索框输入
                    if (!string.IsNullOrEmpty(SearchText))
                    {
                        query = query.Where(e => e.Brand.Contains(SearchText));
                    }

                    var elements = query.OrderByDescending(e => e.Id).ToList();
                    Elements.Clear();
                    foreach (var element in elements)
                    {
                        Elements.Add(element);
                    }
                    UpdatePagedElements();
        }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"品牌搜索失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void UpdatePagedPhysicalProperties()
        {
            if (PhysicalProperties == null || !PhysicalProperties.Any())
            {
                TotalItems = 0;
                TotalPages = 0;
                CurrentPage = 1;
                RaisePropertyChanged(nameof(PageInfo));
                return;
            }

            TotalItems = PhysicalProperties.Count;
            TotalPages = (int)Math.Ceiling((double)TotalItems / PageSize);

            // 确保当前页在有效范围内
            if (CurrentPage > TotalPages)
        {
                CurrentPage = TotalPages;
            }
            else if (CurrentPage < 1)
            {
                CurrentPage = 1;
            }

            // 显式通知 PageInfo 属性变更
            RaisePropertyChanged(nameof(PageInfo));
        }

        private void FilterPhysicalPropertiesByBrand()
        {
            try
            {
                using (var db = SqlSugarHelper.GetInstance())
                {
                    var query = db.Queryable<PhysicalProperties>();

                    if (!string.IsNullOrEmpty(PhysicalSearchText))
                    {
                        query = query.Where(it => it.Brand.Contains(PhysicalSearchText));
                    }

                    var properties = query.OrderByDescending(it => it.Id).ToList();
                    PhysicalProperties.Clear();
                    foreach (var property in properties)
                    {
                        PhysicalProperties.Add(property);
                    }
                    UpdatePagedPhysicalProperties();
                }
            }
            catch (Exception ex)
        {
                MessageBox.Show($"物理性能牌号搜索失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteArchive()
        {
            var infoSummaryViewModel = (Application.Current as App)?.Container.Resolve<InfoSummaryViewModel>();
            if (infoSummaryViewModel != null)
            {
                // 重新加载未归档数据
                infoSummaryViewModel.LoadUnarchivedElements();
                
                var infoSummaryView = new InfoSummaryView();
                infoSummaryView.Owner = Application.Current.MainWindow;
                infoSummaryView.ShowDialog();
            }
        }

        private void ExecuteManagePerson()
        {
            var infoSummaryViewModel = (Application.Current as App)?.Container.Resolve<InfoSummaryViewModel>();
            if (infoSummaryViewModel != null)
            {
                var personManagementView = new PersonManagementView(infoSummaryViewModel.AnalystList, infoSummaryViewModel.VerifierList)
                {
                    Owner = Application.Current.MainWindow
                };
                personManagementView.ShowDialog();
            }
        }

        private void ExecuteExport()
        {
            try
            {
                var dialog = new ExportDialog();
                if (dialog.ShowDialog() == true)
                {
                    var selectedYear = dialog.SelectedYear;
                    var selectedMonth = dialog.SelectedMonth;
                    var selectedBrand = dialog.SelectedBrand; // 新增

                    using (var db = new SqlSugarHelper().GetInstance())
                    {
                        var query = db.Queryable<Element>()
                            .MergeTable()
                            .LeftJoin<Archive>((e, a) => e.ArchiveId == a.Id)
                            .Where(e => e.IsArchived == true)
                            .Select((e, a) => new
                            {
                                Date = e.Date,
                                Brand = e.Brand,
                                Transfernumber = e.Transfernumber,
                                Al = e.Al,
                                Si = e.Si,
                                Fe = e.Fe,
                                Cu = e.Cu,
                                Mn = e.Mn,
                                Mg = e.Mg,
                                Cr = e.Cr,
                                Ni = e.Ni,
                                Zn = e.Zn,
                                Ti = e.Ti,
                                Be = e.Be,
                                Ca = e.Ca,
                                Co = e.Co,
                                Ga = e.Ga,
                                Na = e.Na,
                                P = e.P,
                                Pb = e.Pb,
                                Sb = e.Sb,
                                Sn = e.Sn,
                                Sr = e.Sr,
                                V = e.V,
                                Zr = e.Zr,
                                Analyst = a.Analyst,
                                Verifier = a.Verifier,
                                ArchiveWeight = a.ArchiveWeight,
                                ArchiveDate = a.ArchiveDate,
                                Shift = a.Shift,
                                ArchiveBatchNumber = e.ArchiveBatchNumber
                            });

                        // 根据选择的年份和月份筛选数据
                        if (selectedYear.HasValue)
                        {
                            var startDate = new DateTime(selectedYear.Value, 1, 1);
                            var endDate = new DateTime(selectedYear.Value, 12, 31, 23, 59, 59);
                            if (selectedMonth.HasValue)
                            {
                                startDate = new DateTime(selectedYear.Value, selectedMonth.Value, 1, 0, 0, 0);
                                // 取本月最后一天的23:59:59
                                var daysInMonth = DateTime.DaysInMonth(selectedYear.Value, selectedMonth.Value);
                                endDate = new DateTime(selectedYear.Value, selectedMonth.Value, daysInMonth, 23, 59, 59);
                            }
                            query = query.Where(e => e.Date >= startDate && e.Date <= endDate);
                        }
                        // 新增：根据牌号筛选
                        if (!string.IsNullOrEmpty(selectedBrand) && selectedBrand != "全部")
                        {
                            query = query.Where(e => e.Brand.StartsWith(selectedBrand));
                        }

                        var elements = query.ToList();

                        if (elements.Count == 0)
                        {
                            MessageBox.Show("没有找到符合条件的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }

                        var saveFileDialog = new SaveFileDialog
                        {
                            Filter = "Excel文件|*.xlsx",
                            Title = "保存Excel文件",
                            FileName = $"成分信息_{selectedYear}{(selectedMonth.HasValue ? $"_{selectedMonth}月" : "")}.xlsx"
                        };

                        if (saveFileDialog.ShowDialog() == true)
                        {
                            using (var package = new ExcelPackage())
                            {
                                var worksheet = package.Workbook.Worksheets.Add("成分信息");

                                // 添加表头
                                worksheet.Cells[1, 1].Value = "日期";
                                worksheet.Cells[1, 2].Value = "牌号";
                                worksheet.Cells[1, 3].Value = "中转包次号";
                                worksheet.Cells[1, 4].Value = "Al";
                                worksheet.Cells[1, 5].Value = "Si";
                                worksheet.Cells[1, 6].Value = "Fe";
                                worksheet.Cells[1, 7].Value = "Cu";
                                worksheet.Cells[1, 8].Value = "Mn";
                                worksheet.Cells[1, 9].Value = "Mg";
                                worksheet.Cells[1, 10].Value = "Cr";
                                worksheet.Cells[1, 11].Value = "Ni";
                                worksheet.Cells[1, 12].Value = "Zn";
                                worksheet.Cells[1, 13].Value = "Ti";
                                worksheet.Cells[1, 14].Value = "Be";
                                worksheet.Cells[1, 15].Value = "Ca";
                                worksheet.Cells[1, 16].Value = "Co";
                                worksheet.Cells[1, 17].Value = "Ga";
                                worksheet.Cells[1, 18].Value = "Na";
                                worksheet.Cells[1, 19].Value = "P";
                                worksheet.Cells[1, 20].Value = "Pb";
                                worksheet.Cells[1, 21].Value = "Sb";
                                worksheet.Cells[1, 22].Value = "Sn";
                                worksheet.Cells[1, 23].Value = "Sr";
                                worksheet.Cells[1, 24].Value = "V";
                                worksheet.Cells[1, 25].Value = "Zr";
                                worksheet.Cells[1, 26].Value = "结论";
                                worksheet.Cells[1, 27].Value = "分析人";
                                worksheet.Cells[1, 28].Value = "确认人";
                                worksheet.Cells[1, 29].Value = "归档重量";
                                worksheet.Cells[1, 30].Value = "归档日期";
                                worksheet.Cells[1, 31].Value = "班次";

                                // 设置表头样式
                                using (var range = worksheet.Cells[1, 1, 1, 31])
                                {
                                    range.Style.Font.Bold = true;
                                    range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                                    range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                                }

                                // 按归档批号分组
                                var groupedElements = elements.GroupBy(e => e.ArchiveBatchNumber).ToList();
                                int row = 2;

                                foreach (var group in groupedElements)
                                {
                                    var firstElement = group.First();
                                    var archiveWeight = firstElement.ArchiveWeight;
                                    var archiveDate = firstElement.ArchiveDate;
                                    var shift = firstElement.Shift;
                                    var groupCount = group.Count();
                                    var startRow = row;

                                    foreach (var element in group)
                                    {
                                        worksheet.Cells[row, 1].Value = element.Date;
                                        worksheet.Cells[row, 1].Style.Numberformat.Format = "yyyy-MM-dd hh:mm;ss";
                                        worksheet.Cells[row, 2].Value = element.Brand;
                                        worksheet.Cells[row, 3].Value = element.Transfernumber;
                                        worksheet.Cells[row, 4].Value = element.Al;
                                        worksheet.Cells[row, 5].Value = element.Si;
                                        worksheet.Cells[row, 6].Value = element.Fe;
                                        worksheet.Cells[row, 7].Value = element.Cu;
                                        worksheet.Cells[row, 8].Value = element.Mn;
                                        worksheet.Cells[row, 9].Value = element.Mg;
                                        worksheet.Cells[row, 10].Value = element.Cr;
                                        worksheet.Cells[row, 11].Value = element.Ni;
                                        worksheet.Cells[row, 12].Value = element.Zn;
                                        worksheet.Cells[row, 13].Value = element.Ti;
                                        worksheet.Cells[row, 14].Value = element.Be;
                                        worksheet.Cells[row, 15].Value = element.Ca;
                                        worksheet.Cells[row, 16].Value = element.Co;
                                        worksheet.Cells[row, 17].Value = element.Ga;
                                        worksheet.Cells[row, 18].Value = element.Na;
                                        worksheet.Cells[row, 19].Value = element.P;
                                        worksheet.Cells[row, 20].Value = element.Pb;
                                        worksheet.Cells[row, 21].Value = element.Sb;
                                        worksheet.Cells[row, 22].Value = element.Sn;
                                        worksheet.Cells[row, 23].Value = element.Sr;
                                        worksheet.Cells[row, 24].Value = element.V;
                                        worksheet.Cells[row, 25].Value = element.Zr;
                                        worksheet.Cells[row, 26].Value = "合格";
                                        worksheet.Cells[row, 27].Value = element.Analyst;
                                        worksheet.Cells[row, 28].Value = element.Verifier;
                                        worksheet.Cells[row, 29].Value = archiveWeight;
                                        worksheet.Cells[row, 30].Value = archiveDate;
                                        worksheet.Cells[row, 30].Style.Numberformat.Format = "yyyy-MM-dd";
                                        worksheet.Cells[row, 31].Value = shift;
                                        row++;
                                    }

                                    // 合并相同批次的归档信息单元格
                                    if (groupCount > 1)
                                    {
                                        // 合并归档重量单元格
                                        worksheet.Cells[startRow, 29, startRow + groupCount - 1, 29].Merge = true;
                                        worksheet.Cells[startRow, 29].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                                        // 合并归档日期单元格
                                        worksheet.Cells[startRow, 30, startRow + groupCount - 1, 30].Merge = true;
                                        worksheet.Cells[startRow, 30].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                                        // 合并班次单元格
                                        worksheet.Cells[startRow, 31, startRow + groupCount - 1, 31].Merge = true;
                                        worksheet.Cells[startRow, 31].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                                    }
                                }

                                // 自动调整列宽
                                worksheet.Cells.AutoFitColumns();

                                // 保存文件
                                package.SaveAs(new FileInfo(saveFileDialog.FileName));
                            }

                            MessageBox.Show("导出成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                            // 打开导出的Excel文件
                            try
                            {
                                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                                {
                                    FileName = saveFileDialog.FileName,
                                    UseShellExecute = true
                                });
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"打开文件失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecutePhysicalExport()
        {
            try
            {
                var dialog = new ExportDialog();
                if (dialog.ShowDialog() == true)
                {
                    var selectedYear = dialog.SelectedYear;
                    var selectedMonth = dialog.SelectedMonth;
                    var selectedBrand = dialog.SelectedBrand;

                    using (var db = new SqlSugarHelper().GetInstance())
                    {
                        var query = db.Queryable<PhysicalProperties>();

                        // 年月筛选
                        if (selectedYear.HasValue)
                        {
                            var startDate = new DateTime(selectedYear.Value, 1, 1);
                            var endDate = new DateTime(selectedYear.Value, 12, 31, 23, 59, 59);
                            if (selectedMonth.HasValue)
                            {
                                startDate = new DateTime(selectedYear.Value, selectedMonth.Value, 1, 0, 0, 0);
                                var daysInMonth = DateTime.DaysInMonth(selectedYear.Value, selectedMonth.Value);
                                endDate = new DateTime(selectedYear.Value, selectedMonth.Value, daysInMonth, 23, 59, 59);
                            }
                            query = query.Where(e => e.Date >= startDate && e.Date <= endDate);
                        }
                        // 牌号筛选
                        if (!string.IsNullOrEmpty(selectedBrand) && selectedBrand != "全部")
                        {
                            query = query.Where(e => e.Brand.StartsWith(selectedBrand));
                        }

                        var properties = query.OrderBy(it => it.Id).ToList();

                        if (properties.Count == 0)
                        {
                            MessageBox.Show("没有找到符合条件的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }

                        var saveFileDialog = new SaveFileDialog
                        {
                            Filter = "Excel文件|*.xlsx",
                            Title = "导出物理性能数据",
                            FileName = $"物理性能数据_{selectedYear}{(selectedMonth.HasValue ? $"_{selectedMonth}月" : "")}.xlsx"
                        };

                        if (saveFileDialog.ShowDialog() == true)
                        {
                            using (var package = new ExcelPackage())
                            {
                                var worksheet = package.Workbook.Worksheets.Add("物理性能数据");

                                // 添加表头
                                worksheet.Cells[1, 1].Value = "ID";
                                worksheet.Cells[1, 2].Value = "日期";
                                worksheet.Cells[1, 3].Value = "牌号";
                                worksheet.Cells[1, 4].Value = "抗拉强度";
                                worksheet.Cells[1, 5].Value = "屈服强度";
                                worksheet.Cells[1, 6].Value = "伸长率";
                                worksheet.Cells[1, 7].Value = "硬度";
                                worksheet.Cells[1, 8].Value = "含氢量";
                                worksheet.Cells[1, 9].Value = "金相";
                                worksheet.Cells[1, 10].Value = "断口";
                                worksheet.Cells[1, 11].Value = "创建时间";
                                worksheet.Cells[1, 12].Value = "更新时间";

                                // 设置表头样式
                                using (var range = worksheet.Cells[1, 1, 1, 12])
                                {
                                    range.Style.Font.Bold = true;
                                    range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                                    range.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                                    range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                                }

                                // 添加数据
                                int row = 2;
                                foreach (var item in properties)
                                {
                                    worksheet.Cells[row, 1].Value = item.Id;
                                    worksheet.Cells[row, 2].Value = item.Date?.ToString("yyyy-MM-dd");
                                    worksheet.Cells[row, 3].Value = item.Brand;
                                    worksheet.Cells[row, 4].Value = item.TensileStrength;
                                    worksheet.Cells[row, 5].Value = item.YieldStrength;
                                    worksheet.Cells[row, 6].Value = item.Elongation;
                                    worksheet.Cells[row, 7].Value = item.Hardness;
                                    worksheet.Cells[row, 8].Value = item.HydrogenContent;
                                    worksheet.Cells[row, 9].Value = item.Metallographic;
                                    worksheet.Cells[row, 10].Value = item.Fracture;
                                    worksheet.Cells[row, 11].Value = item.CreateTime?.ToString("yyyy-MM-dd HH:mm:ss");
                                    worksheet.Cells[row, 12].Value = item.UpdateTime?.ToString("yyyy-MM-dd HH:mm:ss");
                                    row++;
                                }

                                // 自动调整列宽
                                worksheet.Cells.AutoFitColumns();

                                // 保存文件
                                package.SaveAs(new FileInfo(saveFileDialog.FileName));
                            }

                            MessageBox.Show("导出成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                            // 打开导出的Excel文件
                            try
                            {
                                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                                {
                                    FileName = saveFileDialog.FileName,
                                    UseShellExecute = true
                                });
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"打开文件失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}